//
//  AlbumLogic.m
//  SecretAlbums
//
//  Created by BabyFinancial on 15/6/16.
//  Copyright (c) 2015年 BabyFinancial. All rights reserved.
//

#import "AlbumLogic.h"
#import "Album.h"
#import "Video.h"
#import "MagicalRecord.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "ALAsset+assetType.h"
#import "NSDateFormatter+timeIntervalFormatter.h"
#import "AlbumPersistence.h"

@interface AlbumLogic ()

// 当前登录相册ID，登录成功时进行赋值，删除或者注销相册时清空
@property (nonatomic, strong) NSString *currentAlbumID;

@end

@implementation AlbumLogic

static AlbumLogic *sharedManager = nil;
+ (instancetype)sharedManager
{
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        sharedManager = [AlbumLogic new];
        sharedManager.currentAlbumID = [NSString new];
    });
    
    return sharedManager;
}

/** 创建相册 */
+ (void)createAlbumWithID:(NSString *)albumID
{
    NSArray *albumArray = [Album MR_findByAttribute:@"albumID" withValue:albumID];
    
    if (0 == albumArray.count) {
        Album *album = [Album MR_createEntity];
        album.albumID = albumID;
        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
        [[AlbumPersistence sharedManager] createDirectoryAtAlbumID:albumID];
    }
}

/** 删除相册并清空当前登录相册ID（必须为登录状态） */
+ (void)removeAlbum
{
    ;
}

/** 登录相册并设置当前登录相册ID */
+ (BOOL)loginWithID:(NSString *)albumID
{
    sharedManager = [AlbumLogic sharedManager];
    NSArray *albumArray = [Album MR_findByAttribute:@"albumID" withValue:albumID];
    
    if (0 != albumArray.count) {
        sharedManager.currentAlbumID = albumID;
        return YES;
    } else {
        return NO;
    }
}

/** 注销相册并清空当前登录相册ID（必须为登录状态） */
+ (void)logout
{
    sharedManager = [AlbumLogic sharedManager];
    sharedManager.currentAlbumID = @"";
}

/** 获取当前相册ID */
+ (NSString *)currentAlbumID
{
    sharedManager = [AlbumLogic sharedManager];
    return sharedManager.currentAlbumID;
}

/** 获取当前相册ID中的缩略图（必须为登录状态） */
+ (NSArray *)thumbnailWithCurrentAlbumID
{
    sharedManager = [AlbumLogic sharedManager];
    Album *album = [Album MR_findByAttribute:@"albumID" withValue:sharedManager.currentAlbumID].firstObject;
    NSArray *sortDesc = @[[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]];
    NSArray *thumbnailArray = [album.thumbnail sortedArrayUsingDescriptors:sortDesc];
    
    return thumbnailArray;
}

/** 获取缩略图对应的原型缩略图路径（必须为登录状态） */
+ (NSString *)aspectRatioThumbnailFilePathAtThumbnail:(Thumbnail *)thumbnail
{
    sharedManager = [AlbumLogic sharedManager];
    NSString *directoryPath = [[AlbumPersistence sharedManager] applicationDocumentsAspectRatioThumbnailDirectoryAtAlbumID:sharedManager.currentAlbumID];
    NSString *filePath = [directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", thumbnail.name]];
    
    return filePath;
}

/** 获取缩略图对应的Photo对象（必须为登录状态） */
+ (Photo *)photoAtThumbnail:(Thumbnail *)thumbnail
{
    NSArray *photoArray = [Photo MR_findByAttribute:@"name" withValue:thumbnail.name];
    
    return photoArray.firstObject;
}

/** 获取缩略图对应的照片路径（必须为登录状态） */
+ (NSString *)photoFilePathAtThumbnail:(Thumbnail *)thumbnail
{
    sharedManager = [AlbumLogic sharedManager];
    NSString *directoryPath = [[AlbumPersistence sharedManager] applicationDocumentsPhotoDirectoryAtAlbumID:sharedManager.currentAlbumID];
    NSString *filePath = [directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", thumbnail.name]];
    
    return filePath;
}

/** 获取缩略图对应的视频路径（必须为登录状态） */
+ (NSString *)videoFilePathAtThumbnail:(Thumbnail *)thumbnail
{
    sharedManager = [AlbumLogic sharedManager];
    NSString *directoryPath = [[AlbumPersistence sharedManager] applicationDocumentsVideoDirectoryAtAlbumID:sharedManager.currentAlbumID];
    NSString *filePath = [directoryPath stringByAppendingPathComponent:thumbnail.name];
    
    return filePath;
}

/** 添加照片至当前相册（必须为登录状态） */
+ (void)addAssets:(NSArray *)assets completion:(void (^)(void))completion
{
    if (assets.count <= 0) {
        completion();
        return;
    }
    
    sharedManager = [AlbumLogic sharedManager];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue setMaxConcurrentOperationCount:1];
    
    for (int i=0; i<assets.count; i++) {
        NSDate *date = [NSDate date];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat: @"yyyy-MM-dd-HH-mm-ss-SSS"];
        NSString *dateString = [dateFormatter stringFromDate:date];
        
        ALAsset *asset = assets[i];
        NSString *name = [NSString stringWithFormat:@"%@+%@", dateString, asset.defaultRepresentation.filename];
        NSDictionary *dic = @{@"Asset":asset, @"Name":name};
        
        // 拷贝缩略图-方形 并 保存CoreData
        NSInvocationOperation *operationThumbnail = [[NSInvocationOperation alloc] initWithTarget:sharedManager selector:@selector(copyThumbnailInApplicationDocumentsDirectoryAndSaveCoreData:) object:dic];
        [queue addOperation:operationThumbnail];
        
        // 拷贝缩略图-原型
        NSInvocationOperation *operationAspectRatioThumbnail = [[NSInvocationOperation alloc] initWithTarget:sharedManager selector:@selector(copyAspectRatioThumbnailInApplicationDocumentsDirectory:) object:dic];
        [queue addOperation:operationAspectRatioThumbnail];
        
        // 拷贝高清图-分段处理（1M）
        NSInvocationOperation *lastOperation = [sharedManager lastOperationAndCreateCopyPhotoOperations:dic operationQueue:queue];
        
        if (i == assets.count - 1) {
            [lastOperation setCompletionBlock:^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    completion();
                });
            }];
        }
    }
}

/** 删除照片从当前相册（必须为登录状态） */
+ (void)delAssets:(NSArray *)assets;
{
    
}

#pragma mark - 私有方法

/** 创建分段拷贝高清图队列，返回最后一个节点 */
- (NSInvocationOperation *)lastOperationAndCreateCopyPhotoOperations:(NSDictionary *)dic operationQueue:(NSOperationQueue *)queue
{
    ALAsset *asset = [dic objectForKey:@"Asset"];
    NSString *imageName = [dic objectForKey:@"Name"];
    
    NSUInteger copySize = 1024 * 1024;     // 每次拷贝的数据Size
    NSUInteger copyNum = (NSUInteger)(asset.defaultRepresentation.size / copySize);
    NSUInteger remaindByte = asset.defaultRepresentation.size % copySize;
    
    NSInvocationOperation *lastOperation;
    for (NSUInteger i = 0; i<copyNum; i++) {
        NSUInteger offset = i*copySize;
        NSDictionary *copyDic = @{@"Asset":asset, @"Name":imageName, @"CopySize":@(copySize), @"Offset":@(offset)};
        
        NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:sharedManager selector:@selector(copyPhotoInApplicationDocumentsDirectoryWithData:) object:copyDic];
        if (i == copyNum-1) {
            lastOperation = operation;
        }
        
        [queue addOperation:operation];
    }
    
    if (0 != remaindByte) {
        NSUInteger offset = copyNum * copySize;
        NSDictionary *copyDic = @{@"Asset":asset, @"Name":imageName, @"CopySize":@(copySize), @"Offset":@(offset)};
        
        NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:sharedManager selector:@selector(copyPhotoInApplicationDocumentsDirectoryWithData:) object:copyDic];
        lastOperation = operation;
        
        [queue addOperation:operation];
    }
    
    return lastOperation;
}

/** 分段拷贝高清图到目录 */
- (void)copyPhotoInApplicationDocumentsDirectoryWithData:(NSDictionary *)dic
{
    ALAsset *asset = [dic objectForKey:@"Asset"];
    NSString *imageName = [dic objectForKey:@"Name"];
    NSNumber *copySize = [dic objectForKey:@"CopySize"];
    NSNumber *offset = [dic objectForKey:@"Offset"];
    
    Byte *buffer = (Byte*)malloc(copySize.integerValue);
    NSUInteger buffered = [asset.defaultRepresentation getBytes:buffer fromOffset:offset.integerValue length:copySize.integerValue error:nil];
    NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
    
    // 分段拷贝
    [[AlbumPersistence sharedManager]
     createPhotoAtAlbumID:self.currentAlbumID
     withImageData:data
     withImageName:imageName];
}

/** 拷贝缩略图-方形到系统目录 并 保存CoreData */
- (void)copyThumbnailInApplicationDocumentsDirectoryAndSaveCoreData:(NSDictionary *)dic
{
    // 保存CoreData
    dispatch_async(dispatch_get_main_queue(), ^{
        [sharedManager createEntityWithAsset:dic];
    });
    
    ALAsset *asset = [dic objectForKey:@"Asset"];
    NSString *imageName = [dic objectForKey:@"Name"];
    
    // 缩略图——方形
    [[AlbumPersistence sharedManager]
     createThumbnailAtAlbumID:self.currentAlbumID
     withImageData:UIImagePNGRepresentation([UIImage imageWithCGImage:asset.thumbnail])
     withImageName:imageName];
}

/** 拷贝缩略图-原型到系统目录 */
- (void)copyAspectRatioThumbnailInApplicationDocumentsDirectory:(NSDictionary *)dic
{
    ALAsset *asset = [dic objectForKey:@"Asset"];
    NSString *imageName = [dic objectForKey:@"Name"];
    
    // 缩略图——原形
    [[AlbumPersistence sharedManager]
     createAspectRatioThumbnailAtAlbumID:self.currentAlbumID
     withImageData:UIImageJPEGRepresentation([UIImage imageWithCGImage:asset.aspectRatioThumbnail], 1.0f)
     withImageName:imageName];
}

/** 创建实体并保存coredata */
- (void)createEntityWithAsset:(NSDictionary *)dic
{
    ALAsset *asset = [dic objectForKey:@"Asset"];
    NSString *imageName = [dic objectForKey:@"Name"];
    
    Album *album = [Album MR_findByAttribute:@"albumID" withValue:self.currentAlbumID].firstObject;
    
    Thumbnail *thumbnail = [Thumbnail MR_createEntity];
    thumbnail.name = imageName;
    thumbnail.isVideo = [NSNumber numberWithBool:[asset isVideo]];
    thumbnail.album = album;
    [album addThumbnailObject:thumbnail];
    
    if ([asset isVideo]) {
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        thumbnail.propertyDuration = [df stringFromTimeInterval:[[asset valueForProperty:ALAssetPropertyDuration] doubleValue]];
        
        // 创建Video
    } else {
        // 创建Photo
        Photo *photo = [Photo MR_createEntity];
        photo.name = imageName;
        photo.width = @(asset.defaultRepresentation.dimensions.width);
        photo.height = @(asset.defaultRepresentation.dimensions.height);
        photo.album = album;
        [album addPhotoObject:photo];
    }
    
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
}

@end
